package com.atguigu.gulimall.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.gulimall.auth.feign.MemberFeignService;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimall.gulimall.auth.vo.SocialUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ansi.Ansi8BitColor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @author phil
 * @create 2022-01-13 15:26
 */
@Slf4j
@Controller
public class OAuth2Controller {

    @Autowired
    MemberFeignService memberFeignService;

    @GetMapping("/oauth2.0/gitee/sucess")
    public String gitee(@RequestParam String code, HttpSession httpSession) throws Exception {

        Map<String,String> headers = new HashMap<>();
        Map<String,String> map = new HashMap<>();
        map.put("grant_type", "authorization_code");
        map.put("client_id", "d03e929ed87a0a12deb067b05ad76e767b3a49bdeb2239aba42f42f0782ee5bc");
        map.put("client_secret", "20abd20c9671e44c79f34e910d6b62dda44923cedbb2a4ceb2f40853b254a31e");
        map.put("redirect_uri", "http://auth.gulimall.com/oauth2.0/gitee/sucess");
        map.put("code", code);

        //1、根据code 换取 AccessToken
        HttpResponse response = HttpUtils.doPost("https://gitee.com", "/oauth/token", "post", headers, null, map);
        //2、处理
        if(response.getStatusLine().getStatusCode() == 200){
            //获取到了AccessToken
            String json = EntityUtils.toString(response.getEntity());
            SocialUser socialUser = JSON.parseObject(json, SocialUser.class);
            //1)、当前用户第一次进网站，自动注册（为当前用户生成一个会员信息账号，以后这个社交帐号就对应这个会员）
            //调用远程服务，注册或者登录这个社交用户
            R r = memberFeignService.oauthLogin(socialUser);
            if(r.getCode() == 0){

                MemberRespVo data = r.getData("data", new TypeReference<MemberRespVo>() {});
                log.info("登录成功：用户：{}",data.toString());
                //1、第一次使用session，命令浏览器保存卡号，JSESSIONID这个cookie
                //以后浏览器访问哪个网站就会带上这个网站的cookie
                //TODO 1、默认发的令牌。当前域（解决子域session共享问题）
                //TODO 2、使用JSON的序列化方式来序列化对象到Redis中
                httpSession.setAttribute(AuthServerConstant.LOGIN_USER, data);
                //登陆成功，返回首页
                return "redirect:http://gulimall.com";
            }else{

                return "redirect:http://auth.gulimall.com/login.html";
            }

        }else{
            return "redirect:http://auth.gulimall.com/login.html";
        }

    }

}
